package xkp.lesson.springboot_shiro.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import xkp.lesson.springboot_shiro.dao.UserInfoDao;
import xkp.lesson.springboot_shiro.entity.UserInfo;
import xkp.lesson.springboot_shiro.exception.CustomException;

import javax.annotation.Resource;
import java.util.List;


@Slf4j
@Service
public class UserInfoService {
    private final static Logger logger=LoggerFactory.getLogger(UserInfoService.class);

    @Resource
    private UserInfoDao userInfoDao;

    public UserInfo findByName(String username) {
        return userInfoDao.selectUserInfoByName(username);
    }

    public List<UserInfo> selectAll(){
        return userInfoDao.selectAll();
    }

    public UserInfo login(String userName,String userPwd) {

        // 1、获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();



        // 2、判断当前用户是否登录
        if (currentUser.isAuthenticated() == false) {
            // 3、将用户名和密码封装到UsernamePasswordToken
           // UsernamePasswordToken token = new UsernamePasswordToken(username, userpwd,true);
            UsernamePasswordToken token = new UsernamePasswordToken(userName, userPwd);

            // 4、认证
            try {
                currentUser.login(token);// 传到MyAuthorizingRealm类中的方法进行认证

                //Session session = currentUser.getSession();
                //session.setAttribute("username", username);
                logger.info("用户名或密码正确");
            } catch (AuthenticationException e) {
                //throw new ResultException("密码或用户名错误");
                logger.info("用户名或密码错误");
                throw new CustomException("用户名或密码错误",222);
            }
        }
        UserInfo userInfo = (UserInfo) currentUser.getPrincipal();
        userInfo.setToken(currentUser.getSession().getId());
        log.info(currentUser.getSession().getId().toString());
        return userInfo;
    }

}
